//
//  LJAddressPicker.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/9/3.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "LJAddressPicker.h"

@interface LJAddressPicker () <UIPickerViewDelegate,UIPickerViewDataSource>

@property (strong, nonatomic) NSArray <LJAddressProvinceModel *>*provinceArray;
@property (strong, nonatomic) NSArray <LJAddressProvinceModel *>*cityArray;
@property (strong, nonatomic) NSArray <LJAddressProvinceModel *>*townArray;
@property (strong, nonatomic) UIPickerView *pickView;
@property(nonatomic, strong) UIView *baseView;  //设置一下背景View

@end

@implementation LJAddressPicker

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = [[UIScreen mainScreen] bounds];
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self getAddressInformation];
        [self setBaseView];
    }
    return self;
}

- (void)getAddressInformation {
    [HttpRequest PostWithApi:ReceiptDeliveryAddressList params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.provinceArray = [LJAddressProvinceModel mj_objectArrayWithKeyValuesArray:responseObject];
            self.cityArray = self.provinceArray.firstObject.children;
            self.townArray = self.cityArray.firstObject.children;
            [self.pickView reloadAllComponents];
            [self.pickView selectRow:0 inComponent:0 animated:YES];
            [self.pickView selectRow:0 inComponent:1 animated:YES];
            [self.pickView selectRow:0 inComponent:2 animated:YES];
            [self updateAddress];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

- (void)setBaseView {
    self.baseView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH, ScreenW, 250 + BottomHeight)];
    self.baseView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.baseView];
    
    self.pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 205)];
    self.pickView.delegate = self;
    self.pickView.dataSource = self;
    [self.baseView addSubview:self.pickView];
    
    //设置取消按钮
    UIButton *cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame  = CGRectMake(0, 205, ScreenW/2, 45);
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:HexColor(0x999999) forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [self.baseView addSubview:cancleBtn];

    //设置确定按钮
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    sureBtn.frame = CGRectMake(ScreenW/2, 205, ScreenW/2, 45);
    [sureBtn setTitle:@"完成" forState:UIControlStateNormal];
    [sureBtn setTitleColor:HexColor(0x999999) forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(finishClick) forControlEvents:UIControlEventTouchUpInside];
    [self.baseView addSubview:sureBtn];
    [self.pickView reloadAllComponents];
    [self updateAddress];
}

- (void)updateAddress {
    self.province = [self.provinceArray objectAtIndex:[self.pickView selectedRowInComponent:0]];
    self.city  = [self.cityArray objectAtIndex:[self.pickView selectedRowInComponent:1]];
    self.town  = [self.townArray objectAtIndex:[self.pickView selectedRowInComponent:2]];
}

- (void)updateAddressAtProvince:(NSString *)province city:(NSString *)city town:(NSString *)town {
//    self.province = province;
//    self.city = city;
//    self.town = town;
    if (self.province) {
        [self.provinceArray enumerateObjectsUsingBlock:^(LJAddressProvinceModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name isEqualToString:province]) {
                [self.pickView selectRow:idx inComponent:0 animated:YES];
            }
        }];
        [self.cityArray enumerateObjectsUsingBlock:^(LJAddressProvinceModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name isEqualToString:city]) {
                [self.pickView selectRow:idx inComponent:1 animated:YES];
            }
        }];
        [self.townArray enumerateObjectsUsingBlock:^(LJAddressProvinceModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name isEqualToString:town]) {
                [self.pickView selectRow:idx inComponent:2 animated:YES];
            }
        }];
    }
    [self.pickView reloadAllComponents];
    [self updateAddress];
}

- (void)pickerViewShow {
    [MAIN_WINDOW addSubview:self];
    [UIView animateWithDuration:0.2 animations:^{
        self.baseView.nim_top =ScreenH-250-BottomHeight;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.baseView.nim_top = ScreenH-250-BottomHeight;
        } completion:^(BOOL finished) {
            
        }];
    }];
}

//点击完成按钮的传值
-(void)finishClick{
    self.finishBlock(self.province, self.city, self.town);
    [self hide];
}

//取消按钮的点击事件
-(void)hide{
    [UIView animateWithDuration:0.2 animations:^{
        self.baseView.nim_top = ScreenH;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self hide];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:self.font?:[UIFont boldSystemFontOfSize:14]];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    } else {
        return self.townArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row].name;
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row].name;
    } else {
        return [self.townArray objectAtIndex:row].name;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return self.frame.size.width / 3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.cityArray = self.provinceArray[row].children;
        self.townArray = self.cityArray[0].children;
//        self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:row]];
//        if (self.selectedArray.count > 0) {
//            self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
//        } else {
//            self.cityArray = @[];
//        }
//        if (self.cityArray.count > 0) {
//            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
//        } else {
//            self.townArray = @[];
//        }
        [pickerView reloadComponent:1];
        [pickerView selectedRowInComponent:1];
        [pickerView reloadComponent:2];
        [pickerView selectedRowInComponent:2];
    }
    if (component == 1) {
//        self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:[self.pickView selectedRowInComponent:0]]];
//        NSDictionary *dic = self.selectedArray.firstObject;
//        NSString *stirng = self.cityArray[row];
//        for (NSString *string in dic.allKeys) {
//            if ([stirng isEqualToString:string]) {
//                self.townArray = dic[string];
//            }
//        }
        self.townArray = self.cityArray[row].children;
        [pickerView reloadComponent:2];
        [pickerView selectedRowInComponent:2];
    }
    if (component == 2) {
        [pickerView reloadComponent:2];
        [pickerView selectedRowInComponent:2];
    }
    [self updateAddress];
}

@end

@implementation LJAddressProvinceModel

+(NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{@"Id":@"id"};
}

+ (NSDictionary *)mj_objectClassInArray {
    return @{@"children":@"LJAddressProvinceModel"};
}

@end
